package com.zxp.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxp.mall.common.utils.PageUtils;
import com.zxp.mall.common.utils.Query;
import com.zxp.mall.product.dao.CategoryDao;
import com.zxp.mall.product.entity.CategoryEntity;
import com.zxp.mall.product.service.CategoryBrandRelationService;
import com.zxp.mall.product.service.CategoryService;
import com.zxp.mall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
//        1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildrens(menu, entities));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 :
                            menu2.getSort());
                })
                .collect(Collectors.toList());
//        2.组装父子树形数据
        return level1Menus;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                })
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 :
                            menu2.getSort());
                }).collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
//        先检查 todo 是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }


    @Override
    public void updateSort(List<CategoryEntity> list) {
        this.updateBatchById(list);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = this.findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
//        收集当前节点id
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId);
        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), paths);
        }
        return paths;
    }

//    @CacheEvict(value = "category",key = "'getLevel1Categorys'")
//    同时进行多种操作
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'"),
    })
//    @CacheEvict(value = "category", allEntries = true) # 删除category分区
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    @Cacheable(value = {"category"}, key = "#root.method.name") // 如果缓存中有 则方法不调用 否则会调用方法 然后把结果缓存起来
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> entities = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println(entities.size());
        return entities;
    }

    @Cacheable(value = {"category"}, key="#root.method.name")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        return this.getDataFromDb();
    }

    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catalog2Vo>> catelogJsonFromDb = getStringListMapWithRedissonLock();

            return catelogJsonFromDb;
        }
        Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String,
                List<Catalog2Vo>>>() {
        });
        return result;
    }

    //    从数据库查询并封装的数据
    private Map<String, List<Catalog2Vo>> getStringListMapWithRedissonLock() {

        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    //    从数据库查询并封装的数据
    private Map<String, List<Catalog2Vo>> getStringListMapWithRedisLock() {
//        redis setNX 的命令
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
//            加锁成功
            Map<String, List<Catalog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
//            把锁删除了 允许别人来占锁
//            这样的情况会导致删除了别人的锁
//            String lockValue = redisTemplate.opsForValue().get("key");
//            if (uuid.equals(lockValue)) {
//                redisTemplate.delete("key");
//            }
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList(
                                "lock"),
                        uuid);
            }
            return dataFromDb;
        } else {
//            加锁失败 重试操作(自旋)
            try {
                Thread.sleep(3 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return this.getStringListMapFromDb();
        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        //        将数据库的多次查询变成一次查询
        List<CategoryEntity> selectList = this.list();

        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        Map<String, List<Catalog2Vo>> map =
                level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
//            查一级分类下的二级分 类
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                    List<Catalog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(l2 -> {
                            Catalog2Vo catelog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(),
                                    l2.getName());
                            List<CategoryEntity> level3Catelogs = getParent_cid(selectList, l2.getCatId());
                            if (level3Catelogs != null) {
                                List<Catalog2Vo.Catalog3Vo> collect = level3Catelogs.stream().map(l3 -> {
                                    Catalog2Vo.Catalog3Vo catelog3Vo = new Catalog2Vo.Catalog3Vo(l3.getCatId().toString(),
                                            l3.getName(),
                                            l2.getCatId().toString());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(collect);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }));
        return map;
    }

    //    本地锁 从数据库查询并封装的数据
    private Map<String, List<Catalog2Vo>> getStringListMapFromDb() {
        synchronized (this) {
            //        将数据库的多次查询变成一次查询
            return getDataFromDb();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }
}